<script setup lang="ts">
import type { Choice } from '@/api/subject/type';
import { ref, watch } from 'vue';

const props = defineProps<{
  choice: Choice;
  modelValue: string | string[]; 
  disabled?: boolean;
}>();

const emit = defineEmits(['update:modelValue']);

const answer = ref(props.modelValue);

// 更新答案
const updateAnswer = (value: string | string[]) => {
  answer.value = value;
  emit('update:modelValue', value);
};

watch(() => props.modelValue, (newValue) => {
  answer.value = newValue; // 同步更新答案
});
</script>

<template>
  <div class="choice-answer">
    <!-- 单选题 -->
    <van-radio-group 
      v-if="!choice.isMultiple" 
      v-model="answer" 
      @change="updateAnswer"
      :disabled="disabled"
    >
      <div 
        v-for="(option, index) in choice.options" 
        :key="index"
        class="choice-option"
        :class="{ 'disabled': disabled }"
      >
        <van-radio 
          :name="option"
          :checked-color="disabled ? '#909399' : '#409eff'"
        >
          <div class="option-content">
            <span class="option-label">{{ String.fromCharCode(65 + index) }}.</span>
            <span class="option-text">{{ option }}</span>
          </div>
        </van-radio>
      </div>
    </van-radio-group>

    <!-- 多选题 -->
    <van-checkbox-group 
      v-else 
      v-model="answer" 
      @change="val => updateAnswer(val)"
      :disabled="disabled"
    >
      <div 
        v-for="(option, index) in choice.options" 
        :key="index"
        class="choice-option"
        :class="{ 'disabled': disabled }"
      >
        <van-checkbox 
          :name="option"
          :checked-color="disabled ? '#909399' : '#409eff'"
        >
          <div class="option-content">
            <span class="option-label">{{ String.fromCharCode(65 + index) }}.</span>
            <span class="option-text">{{ option }}</span>
          </div>
        </van-checkbox>
      </div>
    </van-checkbox-group>
  </div>
</template>

<style lang="scss" scoped>
.choice-answer {
  .choice-option {
    border: 1px solid #ebeef5;
    border-radius: 8px;
    padding: 12px 16px;
    margin-bottom: 12px;
    transition: all 0.2s;
    
    &:hover:not(.disabled) {
      border-color: #c6e2ff;
      background-color: #f5faff;
    }
    
    &.disabled {
      cursor: not-allowed;
      opacity: 0.8;
    }
    
    .option-content {
      display: flex;
      align-items: center;
      
      .option-label {
        flex-shrink: 0;
        margin-right: 8px;
        font-weight: 500;
      }
      
      .option-text {
        flex: 1;
      }
    }
  }
}
</style>
